import apiConfig from './apiConfig'
import template from 'url-template'
import qs from 'qs'
import { RequestQueue } from './request-queue'
import { isSuccess } from '@/api/request/util'
const requestQueue = new RequestQueue()
export const request = ({ type = 'get', apiName, path, params = {}, config = {} } = {}) => {
  return new Promise((resolve, reject) => {
    const fullPath = apiName !== '' ? apiConfig[apiName] + path : path
    const templateUrl = template.parse(fullPath)
    const url = templateUrl.expand(params)
    const requestType = type.toLocaleLowerCase()
    let data
    if (['post', 'put'].includes(requestType)) {
      if (config.form) {
        data = qs.stringify(params)
        delete config.form
        config.header = Object.assign(
          {},
          config.header,
          { 'Content-Type': 'application/x-www-form-urlencoded' })
      }
    }
    if (['get', 'delete'].includes(requestType)) {
      config.params = params
    }
    requestQueue.request({ type: requestType, url, data, config }).then(res => {
      if (isSuccess(res, config)) { // 当options中明确指出不需要成功code时 直接返回
        resolve(res.data)
      } else {
        if (res.data && res.data.message) {
          // ElMessage.error(res.data.message)
        }
        reject(res.data)
      }
    }).catch(res => {
      // ElMessage.error(res.message)
      reject(res)
    })
  })
}
